<template>
  <div class="confirmOrder">

    <shade v-show="loadShow"/>

    <div class="receiveInfo" @click="toAddrList">
      <div>
        <div>
          <span class="iconfont icon-dingwei"></span>
          <span class="receivePeople">收货人：{{ defaultAddr.nickname || defaultAddr}}</span>
        </div>
        <span class="receiveTel">联系电话：{{ defaultAddr.tel || defaultAddr}}</span>
      </div>
      <p>收货地址：{{ defaultAddr.province + defaultAddr.city + defaultAddr.area + defaultAddr.address || defaultAddr}}</p>
    </div>
    <!-- 付款方式 -->
    <div class="pay_style">
      <p class="pay_title">支付方式</p>
      <div class="pay wxpay iconfont " :class="{gou: zhifuFlag == 'wx'}" @click="zhifuFlag='wx'">
        <span class="iconfont icon-weixinzhifu" style="color: #42B035;font-size: .36rem;"></span>
        微信支付
      </div>
      <div class="pay COD iconfont" :class="{gou: zhifuFlag == 'df'}" @click="zhifuFlag='df'">
        <span class="iconfont icon-zaixianzhifu" style="color: #FFA200;font-size: .36rem;">
        </span>
        到付邮费
      </div>
    </div>
    <!-- 商品信息  -->
    <!-- <orders :countShow="false" :info="info" :state="0"/> -->
    <goodInfo-get :info="info" :is_share="is_share"></goodInfo-get>

    <div class="msgNote">
      <label>给卖家留言</label>
      <textarea rows="3" placeholder="提醒商家注意" v-model="user_note"></textarea>
    </div>

    <p class="total">共1件商品 合计：<span>￥{{ is_share==='yes'? info.package[1].discount_price:info.package[1].price }}</span></p>
    <div class="confirmBtnWrap">
      <p>合计：<span>￥{{ is_share==='yes'? info.package[1].discount_price:info.package[1].price }}</span></p>
      <div class="confirmBtn" @click="payOrder">提交订单</div>
    </div>
  </div>
</template>
<script>
import configWxPayApi from "@/utils/configWxPayApi.js";
import goodInfoGet from "../components/goodInfoGet";
import getCode from "@/utils/getCode";
import { getTeaSamplesInfo } from "@/api/chayang";
import {
  order,
  OrderPay_wxJsapi,
  getUserInfo,
  isLogin,
  getAddrList,
  queryOrder,
  OrderPay_wxh5
} from "@/api/index";
import wx from "weixin-js-sdk";
export default {
  data() {
    return {
      zhifuFlag: 'wx',
      good_id: this.$route.params.good_id,
      is_share: this.$route.params.is_share,
      loadShow: true,
      info: {
        package: {
          "1": {
            price: "",
            name: "",
            discount_price: ''
          }
        }
      },
      user_note: "",
      code: "",
      openid: "",
      defaultAddr: {},
      isClick: false
    };
  },
  created() {
    this.$store.commit("SETPAGEINFO", {
      title: "确认订单",
      description: ""
    });
    getTeaSamplesInfo(this.$store.state.urlParams.good_id).then(results => {
      this.info = results.data;
      // console.log(Object.values(this.info.package));
      this.loadShow = false;
    });
    configWxPayApi();
    wx.ready(() => {});
    wx.error(function(res) {});
    getCode(this);
    isLogin().then(result => {
      // if (result.data.uid!=undefined) {
      //   if (result.data.uid.length == 0) {
      //     this.$router.push("/login");
      //   }
      // }
      this.openid = result.data.openid;
      this.$store.commit("SETOPENID", result.data.openid);
    });
    if (this.$route.params.selectedAddr) {
      this.defaultAddr = this.$route.params.selectedAddr;
    } else {
      getAddrList().then(result => {
        // console.log(result)
        if (result.data.length == 0) {
          this.$router.push({
            name: "添加收货地址",
            params: this.$route.params
          });
        } else {
          result.data.forEach(item => {
            item.is_default == 1 ? (this.defaultAddr = item) : item;
          });
          if (this.defaultAddr.valueOf.length == 0) {
            this.defaultAddr = result.data[0];
          }
        }
      });
    }
  },
  methods: {
    payOrder() {
      if (this.isClick) {
        return false;
      }
      if (
        Boolean(this.defaultAddr.nickname) == false ||
        Boolean(this.defaultAddr.tel) == false ||
        Boolean(this.defaultAddr.province) == false ||
        Boolean(this.defaultAddr.city) == false ||
        Boolean(this.defaultAddr.area) == false
      ) {
        this.$toast("对不起，地址信息获取错误，请返回首页重新下单");
        return false;
      }
      this.isClick = true;
      var loading = this.$toast({
        message: "支付发起中",
        iconClass: "iconfont icon-jiazaizhong1",
        duration: -1
      });
      const orderInfo = {
        pay_style: this.zhifuFlag == 'df' ? 'COD' : this.$store.state.loginType == "wx" ? "wx_jsapi" : "wx_h5",
        platform: this.$store.state.urlParams.platform,
        username: this.$store.state.urlParams.username,
        ad: this.$store.state.urlParams.ad,
        good_id: this.good_id,
        package_id: 1,
        num: 1,
        user_note: this.user_note,
        nickname: this.defaultAddr.nickname,
        tel: this.defaultAddr.tel,
        province: this.defaultAddr.province,
        city: this.defaultAddr.city,
        area: this.defaultAddr.area,
        address: this.defaultAddr.address,
        page_url: location.href,
        share_user_openid: this.$route.params.is_share==='yes' ? this.$store.state.openid : ''
      };
      order(orderInfo)
        .then(result => {
          if (result.data.success == "no") {
            this.$messagebox.alert(result.data.message);
            loading.close();
            return false;
          }
          if(this.zhifuFlag == 'df') {
            loading.close();
            this.$router.push("/paySuccess/" + result.data.order_no);
            return false;
          }
          // 判断是否为H5支付
          if (this.$store.state.loginType == "h5") {
            OrderPay_wxh5(result.data.order_no).then(results => {
              const rdirectUrl =
                "http://www.chamiw.com/App/dist/#/paySuccess/" +
                result.data.order_no;
              location.href =
                decodeURIComponent(results.data.mweb_url) +
                "&redirect_url=" +
                encodeURIComponent(rdirectUrl);
            });
            loading.close();
            return false;
          } else {
            // 微信公众号支付
            OrderPay_wxJsapi(result.data.order_no, this.openid).then(res => {
              wx.chooseWXPay({
                timestamp: res.data.jsApiParameters.timeStamp, // 支付签名时间戳，注意微信jssdk中的所有使用timestamp字段均为小写。但最新版的支付后台生成签名使用的timeStamp字段名需大写其中的S字符
                nonceStr: res.data.jsApiParameters.nonceStr, // 支付签名随机串，不长于 32 位
                package: res.data.jsApiParameters.package, // 统一支付接口返回的prepay_id参数值，提交格式如：prepay_id=\*\*\*）
                signType: res.data.jsApiParameters.signType, // 签名方式，默认为'SHA1'，使用新版支付需传入'MD5'
                paySign: res.data.jsApiParameters.paySign, // 支付签名
                success: res => {
                  queryOrder(result.data.order_no).then(queryRes => {
                    if (queryRes.data.success == "yes") {
                      this.$router.push("/paySuccess/" + result.data.order_no);
                    }
                  });
                }
              });
              loading.close();
            });
          }
        })
        .catch(err => {
          alert(err);
          loading.close();
        });
    },
    toAddrList() {
      this.$router.push({
        name: "收货地址列表",
        params: {
          good_id: this.good_id,
          type: "cy"
        }
      });
    }
  },
  components: {
    goodInfoGet
  }
};
</script>

<style lang="scss" scoped>
@import "@/style/base.scss";
.confirmOrder {
  background-color: #f0f0f0;
  padding-bottom: to(10);
  .receiveInfo {
    height: to(88);
    background-color: #fff;
    padding: to(15);
    box-sizing: content-box;
    margin-bottom: to(15);
    div:nth-child(1) {
      display: -webkit-flex;
      span {
        font-size: to(25);
        line-height: to(35);
        // vertical-align: top;
      }
      div {
        flex: 1;
        .iconfont {
          font-size: to(30);
          color: #404040;
          margin-right: to(10);
        }
        .receivePeople {
          color: #000;
        }
        .receiveTel {
          color: #5b5b5b;
          flex: 1;
          text-align: rightl;
        }
      }
    }
    p {
      font-size: to(21);
      color: #5b5b5b;
      line-height: to(50);
      margin: 0;
    }
  }
  .pay_style {
    background-color: #fff;
    padding: 0 0.28rem;
    margin-bottom: to(20);
    .pay_title {
      height: to(60);
      margin: 0;
      line-height: to(60);
      font-size: to(24);
      color: #858585;
      border-bottom: 1px solid #eee;
    }
    .pay {
      line-height: to(90);
      height: to(90);
      font-size: to(24);
      color: #676767;
      border-bottom: 1px solid #cecece;
      padding-left: 0.8rem;
      position: relative;
      &:nth-child(3) {
        border: 0;
      }
      span {
        line-height: to(90);
        vertical-align: middle;
        position: absolute;
        width: 0.6rem;
        height: 0.6rem;
        left: 0.1rem;
      }
    }
    .gou {
      font-size: to(24);
      &::after {
        content: "\e612";
        color: #ffa200;
        position: absolute;
        right: 0.1rem;
      }
    }
  }
  .msgNote {
    display: -webkit-flex;
    font-size: to(26);
    height: to(180);
    border-bottom: 1px solid #eae9e9;
    background-color: #fff;
    // padding: to(10);
    label {
      flex: 3;
      line-height: to(71);
      color: #404040;
      padding-left: to(16);
    }
    textarea {
      flex: 7;
      border: 0;
      font-size: to(25);
      height: 100%;
      padding: to(15);
      line-height: to(40);
      outline: none;
      &::-webkit-input-placeholder {
        color: #d0d0d0;
      }
    }
  }
  .total {
    margin: to(18) 0;
    font-size: to(30);
    color: #404040;
    text-align: right;
    padding: 0 to(15);
    span {
      color: #aa0000;
    }
  }
  .confirmBtnWrap {
    height: to(103);
    width: 100%;
    text-align: right;
    display: -webkit-flex;
    font-size: to(33);
    justify-content: flex-end;
    position: fixed;
    bottom: 0;
    background-color: #fcfcfc;
    p {
      line-height: to(103);
      color: #404040;
      span {
        color: #aa0000;
      }
      margin-right: to(25);
    }
    div {
      width: to(156);
      height: to(64);
      background-color: #c11414;
      border-radius: to(5);
      line-height: to(64);
      text-align: center;
      color: white;
      margin: to(19) to(9);
      font-size: to(31);
    }
  }
}
</style>
